<script lang="ts" setup>
import { reactive, watch } from 'vue';
import { SYS_ORGAN_QUERY_APP, OPEN_SYS_ORGAN_QUERY_APP } from '/@/api/modules/base/app-sys-organ';

const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    /**
     * 标题
     */
    title?: string;
    /**
     * 是否开放接口
     */
    isOpen?: boolean;
  }>(),
  {
    modelValue: false,
    title: '部门',
    isOpen: false,
  },
);
const emits = defineEmits<{
  (e: 'update:modelValue'): void;
  (e: 'onSelected', activeOrganIds: string[], activeOrgans: AppCascaderOrganDto[]): void;
}>();

const state = reactive<{
  /**
   * 组织树
   */
  organTree: AppSysOrgan.Dto[];
  /**
   * 选中的组织id
   */
  activeOrganIds: string[];
  /**
   * 选中的组织
   */
  activeOrgans: AppCascaderOrganDto[];
}>({
  organTree: [],
  activeOrganIds: [],
  activeOrgans: [],
});

watch(props, (newProps) => {
  if (!newProps.modelValue) return;

  if (newProps.isOpen) {
    OPEN_SYS_ORGAN_QUERY_APP({ comQuery: { page: 1, pageSize: 10000 } }).then((res) => {
      state.organTree = res.content;
    });
  } else {
    SYS_ORGAN_QUERY_APP({ comQuery: { page: 1, pageSize: 10000 } }).then((res) => {
      state.organTree = res.content;
    });
  }
});
</script>

<template>
  <nut-popup
    :visible="props.modelValue"
    position="bottom"
    closeable
    round
    @click-close-icon="emits('update:modelValue')"
    @click-overlay="emits('update:modelValue')"
  >
    <view class="app-popup__header">
      <text>{{ props.title }}</text>
    </view>
    <nut-cascader
      :visible="true"
      v-model="state.activeOrganIds"
      :title="props.title"
      :options="state.organTree"
      :poppable="false"
      text-key="name"
      value-key="id"
      children-key="children"
      @change="(activeOrganIds: string[], activeOrgans: AppCascaderOrganDto[]) => {
        state.activeOrgans = activeOrgans;
        state.activeOrganIds = activeOrganIds;
        emits('onSelected', state.activeOrganIds, state.activeOrgans);
      }"
      @path-change="(activeOrgans: AppCascaderOrganDto[]) => {
        state.activeOrgans = activeOrgans.filter(item => item);
        state.activeOrganIds = activeOrgans.map((item) => {
          if (item && item.value) return item.value;
          return '';
        }).filter(item => item);
        emits('onSelected', state.activeOrganIds, state.activeOrgans);
      }"
    />
    <view class="app-popup__footer">
      <nut-button
        type="primary"
        block
        @click="
          () => {
            emits('onSelected', state.activeOrganIds, state.activeOrgans);
            emits('update:modelValue');
          }
        "
      >
        确认
      </nut-button>
    </view>
  </nut-popup>
</template>
